<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :width="780"
    :visible="visible"
    :confirm-loading="loading"
    :title="isUpdate ? '修改职位' : '新建职位'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 3, sm: 4, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 21, sm: 20, xs: 24 } : { flex: '1' }
      "
    >
      <a-row>
        <a-col :span="24">
          <a-form-item label="岗位名称" name="title">
            <a-input
              allow-clear
              placeholder="请输入岗位名称"
              v-model:value="form.title"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item :label-col="{ span: 6 }" label="所属企业" name="company">
            <company-select v-model:value="company" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            :label-col="{ span: 6 }"
            label="所属分类"
            name="category"
          >
            <cate-select v-model:value="category" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item :label-col="{ span: 6 }" label="招聘人数" name="needs">
            <a-input
              allow-clear
              placeholder="请输入招聘人数"
              v-model:value="form.needs"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item :label-col="{ span: 6 }" label="学历要求" name="degree">
            <a-input
              allow-clear
              placeholder="请输入学历要求"
              v-model:value="form.degree"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item
            :label-col="{ span: 6 }"
            label="工作经历"
            name="seniority"
          >
            <a-input
              allow-clear
              placeholder="请输入工作经历"
              v-model:value="form.seniority"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item :label-col="{ span: 6 }" label="工资待遇" name="salary">
            <a-input
              allow-clear
              placeholder="请输入工作经历"
              v-model:value="form.salary"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-item label="岗位福利" name="tags">
            <tag-select v-model:value="form.tags" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-item label="岗位介绍" name="description">
            <tinymce-editor v-model:value="form.description" :init="config" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue/es';
  import type { FormInstance, Rule } from 'ant-design-vue/es/form';
  import { storeToRefs } from 'pinia';
  import { useThemeStore } from '@/store/modules/theme';
  import useFormData from '@/utils/use-form-data';
  import CompanySelect from './company-select.vue';
  import CateSelect from './category-select.vue';
  import TagSelect from './tag-select.vue';
  import { addJob, updateJob } from '@/api/employ/jobs';
  import { Job } from '@/api/employ/jobs/model';
  import request from '@/utils/request';

  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: Job | null;
  }>();

  //
  const formRef = ref<FormInstance | null>(null);

  // 是否是修改
  const isUpdate = ref(false);

  // 提交状态
  const loading = ref(false);

  // 表单数据
  const { form, resetFields, assignFields } = useFormData<Job>({
    jobId: undefined,
    title: '',
    companyId: '',
    categoryId: undefined,
    needs: '',
    degree: '',
    seniority: '',
    salary: '',
    tags: [],
    description: ''
  });

  const category = ref();
  const company = ref();
  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    title: [
      {
        required: true,
        type: 'string',
        message: '请输入岗位名称',
        trigger: 'blur'
      }
    ],
    description: [
      {
        required: true,
        message: '请输入岗位描述',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });
  const config = ref({
    height: 300,
    external_plugins: {
      editor135: 'http://cdn.cqtlcm.com/plugin/plugin.js'
    },
    toolbar:
      'removeformat forecolor backcolor bold italic underline strikethrough | alignleft aligncenter alignright alignjustify outdent indent | formatselect fontselect editor135',
    plugins:
      'editor135 media image link table code preview fullscreen wordcount',
    automatic_uploads: true,
    paste_data_images: true, // 设置为允许粘帖图片
    images_upload_handler: (blobInfo, success, error) => {
      const file = blobInfo.blob();
      // 使用 axios 上传，实际开发这段建议写在 api 中再调用 api
      const formData = new FormData();
      formData.append('file', file, file.name);
      request({
        url: '/file/upload',
        method: 'post',
        data: formData
      })
        .then((res) => {
          if (res.data.data) {
            success(res.data.data);
          } else {
            error(res.data.message);
          }
        })
        .catch((e) => {
          error(e.message);
        });
    },
    file_picker_callback: (callback, value, meta) => {
      const input = document.createElement('input');
      input.setAttribute('type', 'file');
      // 设定文件可选类型
      if (meta.filetype === 'image') {
        input.setAttribute('accept', 'image/*');
      } else if (meta.filetype === 'media') {
        input.setAttribute('accept', 'video/*');
        //input.setAttribute('accept', 'audio/*');
      }
      input.onchange = () => {
        const file = input.files[0];
        // 使用 axios 上传，实际开发这段建议写在 api 中再调用 api
        const formData = new FormData();
        formData.append('file', file, file.name);
        request({
          url: '/file/upload',
          method: 'post',
          data: formData
        })
          .then((res) => {
            if (res.data.data) {
              callback(res.data.data);
            } else {
              message.error(res.data.message);
            }
          })
          .catch((e) => {
            message.error(e.message);
          });
      };
      input.click();
    }
  });
  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const saveOrUpdate = isUpdate.value ? updateJob : addJob;
        assignFields({
          ...form,
          companyId: company.value[0].companyId,
          categoryId: category.value[0].categoryId
        });
        saveOrUpdate(form)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
    category.value = [];
    company.value = [];
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          company.value = props.data.company;
          category.value = props.data.category;
          assignFields(props.data);
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        formRef.value?.clearValidate();
      }
    }
  );
</script>
